﻿package rd.android.hardcore
{
	import air.update.descriptors.ConfigurationDescriptor;
	import caurina.transitions.Tweener;
	import flash.display.Sprite;
	import flash.display.StageAspectRatio;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.net.URLRequest;
	import fr.digitas.flowearth.conf.Conf;
	import rd.android.hardcore.engine.air.HardcoreUpdater;
	import rd.android.hardcore.engine.HardcoreGhettoSoundSystem;
	import rd.android.hardcore.engine.InitUserConf;
	import rd.android.hardcore.engine.PadsManager;
	import rd.android.hardcore.event.GlobalEvent;
	import rd.android.hardcore.event.SoundSystemEvent;
	import rd.android.hardcore.params.GlobalParams;
	import rd.android.hardcore.ui.footer.Footer;
	import rd.android.hardcore.ui.header.Header;
	
	/**
	 * ...
	 * @author Fazermokeur
	 */
	public class Main extends Sprite 
	{
		private var manager:PadsManager;
		private var header 	: Header;
		private var footer	: Footer;
		private var soundSystem:HardcoreGhettoSoundSystem;
		
		public function Main():void 
		{
			//removeEventListener(Event.ADDED_TO_STAGE, init);
			
			var confFile:String = "xml/config.xml";
			
			Conf.addEventListener(Event.COMPLETE, configLoaded);
			Conf.loadXml( new URLRequest ( confFile ));
		}
		
		private function configLoaded(e:Event):void 
		{
			var initUserConf:InitUserConf = new InitUserConf();
			initUserConf.addEventListener(Event.COMPLETE, display);
			initUserConf.start();
			
			// params
			GlobalParams.PAD_SIZE = Conf.getNumber("sizePad");
			
			GlobalParams.WIDTH = 480;
			GlobalParams.HEIGHT = 800;
		}
		
		private function display(e:Event):void 
		{
			var appUpdate:HardcoreUpdater = new HardcoreUpdater();
			appUpdate.Maj(Conf.getString("updaterXML"));
			
			dispatchEvent(new GlobalEvent(GlobalEvent.MAIN_DISPLAYED));
			
			if (stage) init();
			else addEventListener(Event.ADDED_TO_STAGE, init);
		}
		
		private function init(e:Event = null):void
		{
			trace("Main addedtostage");
			removeEventListener(Event.ADDED_TO_STAGE, init);
			
			header = new Header();
			addChild(header);
			
			footer = new Footer();
			addChild(footer);
			
			manager = new PadsManager();
			addChildAt(manager,0);
			
			soundSystem = new HardcoreGhettoSoundSystem();
			
			addEventListener(SoundSystemEvent.PLAY_SOUND, playSound);
			addEventListener(SoundSystemEvent.KILL_SOUND, stopSound);
		}
		
		private function playSound(e:SoundSystemEvent):void 
		{
			soundSystem.playSound(e);
		}
		
		private function stopSound(e:Event):void 
		{
			soundSystem.closeSound(null);
		}
		
		public function handleResize(e:Event):void
		{
			if (manager) {
				manager.handleResize(e);
			}
		}
	}
	
}